package routers

import (
	"database/sql"
	"net/http"

	"shqsoft.cn/pas3ui/base"
	"shqsoft.cn/pas3ui/entity"
	"shqsoft.cn/pas3ui/popedom"

	jwt "github.com/dgrijalva/jwt-go"
	"github.com/labstack/echo"
)

//MenusInfo 菜单信息
type MenusInfo struct {
	MenuDatas     []Menus               `json:"menuDatas"`
	PopedomTypes  map[int][]string      `json:"popedomTypes"`
	ExtendProps   map[int]string        `json:"extendProps"`
	OdsDate       string                `json:"odsDate"`
	EdwDate       string                `json:"edwDate"`
	FtpDate       string                `json:"ftpDate"`
	CapDate       string                `json:"capDate"`
	FlowDoingList []entity.FlowDoingSum `json:"flowDoingList"`
}

//Menus 系统菜单
type Menus struct {
	ID        int     `json:"id"`
	Path      string  `json:"path"`
	Name      string  `json:"name"`
	Icon      string  `json:"icon"`
	Children  []Menus `json:"routes"`
	Component string  `json:"component"`
}

//Route 前台路由
type Route struct {
	Path      string `json:"path"`
	Name      string `json:"name"`
	Icon      string `json:"icon"`
	Component string `json:"component"`
}

//GetSysName 获取系统名称
func GetSysName(c echo.Context) error {
	return c.String(http.StatusOK, base.AppConf.UseOrgan)
}

//MenuAllRouter 获取所有的有权限的菜单权限
func MenuAllRouter(c echo.Context) error {
	user := c.Get("user").(*jwt.Token)
	claims := user.Claims.(*UserLoginClaims)
	infos, err := base.GetSysInfo()
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	var odsDate, edwDate, ftpDate, capDate string
	for _, info := range infos {
		if info.DataType == "ODS" {
			odsDate = info.SYSDate.Format("2006-01-02")
		} else if info.DataType == "EDW" {
			edwDate = info.SYSDate.Format("2006-01-02")
		} else if info.DataType == "FTP" {
			ftpDate = info.SYSDate.Format("2006-01-02")
		} else {
			capDate = info.SYSDate.Format("2006-01-02")
		}
	}
	menusInfo := MenusInfo{
		PopedomTypes: make(map[int][]string, 150),
		ExtendProps:  make(map[int]string, 150),
		OdsDate:      odsDate,
		EdwDate:      edwDate,
		FtpDate:      ftpDate,
		CapDate:      capDate,
	}
	menusInfo.MenuDatas, err = menusInfo.getMenus(0, "", claims.UserID)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	err = base.MYDB.Where(`EMID=?`, claims.UserID).Find(&menusInfo.FlowDoingList).Error
	if err != nil {
		return err
	}
	return c.JSON(http.StatusOK, menusInfo)
}

func (m MenusInfo) getMenus(permID int, parentPath string, userID int) ([]Menus, error) {
	var menus []entity.Menu
	err := base.MYDB.Where(`IsUse=1 and ParentPermissionId=?`, permID).Order(`SortNo`).Find(&menus).Error
	if err != nil {
		return nil, err
	}
	mlen := len(menus)
	if mlen == 0 {
		return nil, nil
	}
	menus2 := make([]Menus, 0, mlen)
	for i := 0; i < mlen; i++ {
		if menus[i].Name == "首页" {
			continue
		}
		isOk, err := popedom.ValidateUserPermission(userID, menus[i].ID)
		if err != nil {
			return nil, err
		}
		if isOk {
			var m2 Menus
			pTypes, err := popedom.GetUserPermissionTypes(userID, menus[i].ID)
			if err != nil {
				return nil, err
			}
			m.PopedomTypes[menus[i].ID] = pTypes
			m.ExtendProps[menus[i].ID] = menus[i].ExtendProps
			m2.ID = menus[i].ID
			m2.Path = parentPath + "/" + menus[i].No
			m2.Name = menus[i].Name
			m2.Icon = menus[i].Icon
			m2.Component = menus[i].PagePath
			children, err := m.getMenus(menus[i].ID, m2.Path, userID)
			if err != nil {
				return nil, err
			}
			m2.Children = children
			menus2 = append(menus2, m2)
		}
	}
	return menus2, nil
}

//RoutesRouter 获取前台路由列表的路由
func RoutesRouter(c echo.Context) error {
	routes, err := getRoutes()
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	return c.JSON(http.StatusOK, routes)
}

func getRoutes() (routes []Route, err error) {
	var rows *sql.Rows
	rows, err = base.MYDB.Raw(`select ID,PermissionNo,pagePath,ParentPermissionId
	from t_Permission a where not exists(select 0 from t_Permission where ParentPermissionId=a.ID) and IsUse =1 order by SortNo`).Rows()
	if err != nil {
		return
	}
	defer rows.Close()
	routes = make([]Route, 0, 50)
	for rows.Next() {
		var id, pid int
		var name, component, path string
		err = rows.Scan(&id, &name, &component, &pid)
		if err != nil {
			return
		}
		path, err = getRoutePath(pid, name)
		if err != nil {
			return
		}
		routes = append(routes, Route{
			Name:      name,
			Component: component,
			Path:      "/" + path,
		})
	}
	return
}

func getRoutePath(permID int, name string) (path string, err error) {
	if permID == 0 {
		return name, nil
	}
	var pid int
	var no string
	err = base.MYDB.Raw(`select ParentPermissionId ,PermissionNo from t_Permission where ID=?`, permID).Row().Scan(&pid, &no)
	if err != nil {
		return
	}
	path = no + "/" + name
	if pid != 0 {
		return getRoutePath(pid, path)
	}
	return
}
